<template>
  <view class="schedule-container">
    <!-- 头部 -->
    <view class="header-tip">
      <text>{{ userInfo ? `${userInfo.nickname || userInfo.userName}的课程表` : '我的课程表' }}</text>
      <text class="tip-text">点击课程进行修改，点击空白处添加课程</text>
    </view>

    <!-- 操作按钮 -->
    <view class="action-bar">
      <button class="btn-refresh" @click="refreshData">刷新课表</button>
    </view>

    <!-- 课程表格 -->
    <scroll-view scroll-x class="table-scroll">
      <view class="schedule-table">
        <!-- 表头 -->
        <view class="table-header">
          <view class="header-cell time-cell">时间段</view>
          <view class="header-cell" v-for="day in weekDays" :key="day.value">
            {{ day.label }}
          </view>
        </view>

        <!-- 表格内容 -->
        <view class="table-body">
          <view class="table-row" v-for="(section, index) in uniqueSections" :key="index">
            <view class="body-cell time-cell">
              <text class="time-label">{{ section }}</text>
            </view>
            <view 
              class="body-cell schedule-cell" 
              v-for="day in weekDays" 
              :key="day.value"
              @click="handleCellClick(section, day.value)"
            >
              <view 
                class="schedule-item" 
                v-if="getCourseByTime(section, day.value)"
              >
                <view class="course-line">
                  <text class="course-name">{{ getCourseByTime(section, day.value).courseContent }}</text>
                </view>
                <view class="course-line">
                  <text class="class-name">{{ getCourseByTime(section, day.value).className }}</text>
                </view>
                <view class="course-line">
                  <text class="classroom">{{ getCourseByTime(section, day.value).classroom }}</text>
                </view>
              </view>
              <view class="empty-cell" v-else>
                <text class="empty-text">+</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 编辑/添加课程弹窗 -->
    <view class="popup-mask" v-if="showEditModal" @click="closeEditModal">
      <view class="popup-content" @click.stop>
        <view class="popup-title">{{ editingCourse && editingCourse.id ? '修改课程' : '添加课程' }}</view>
        <view class="form-item">
          <text class="form-label">班级</text>
          <input class="form-input" v-model="editingCourse.className" placeholder="请输入班级名称" />
        </view>
        <view class="form-item">
          <text class="form-label">时间段</text>
          <view class="form-value">{{ editingCourse.classSection }} {{ getWeekDayLabel(editingCourse.dayOfWeek) }}</view>
        </view>
        <view class="form-item">
          <text class="form-label">教室</text>
          <input class="form-input" v-model="editingCourse.classroom" placeholder="请输入教室号" />
        </view>
        <view class="form-item">
          <text class="form-label">课程内容 *</text>
          <input 
            class="form-input" 
            v-model="editingCourse.courseContent"
            placeholder="如：语文/张老师"
          />
        </view>
        <view class="popup-buttons">
          <button class="btn-cancel" @click="closeEditModal">取消</button>
          <button class="btn-confirm" @click="submitEdit">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getTeacherSchedule, updateCourseContent, checkTimeConflict } from '@/api/system/schedule'
import { getUserProfile } from '@/api/system/user'

export default {
  data() {
    return {
      // 当前用户信息
      userInfo: null,
      
      // 筛选条件 - 移除周次选择,因为表结构没有周次字段
      currentTerm: '', // 当前学期
      
      // 课程表数据 (格式: TeacherScheduleRespVO[])
      scheduleData: [],
      
      // 编辑相关
      showEditModal: false,
      editingCourse: null, // 正在编辑的课程
      originalCourse: null, // 保存原始数据用于回滚
      
      // 星期数据
      weekDays: [
        { label: '周一', value: 1 },
        { label: '周二', value: 2 },
        { label: '周三', value: 3 },
        { label: '周四', value: 4 },
        { label: '周五', value: 5 },
        { label: '周六', value: 6 },
        { label: '周日', value: 7 }
      ]
    }
  },
  
  computed: {
    // 获取所有唯一的时段列表(如: "早1 08:00-08:20")
    uniqueSections() {
      const sections = this.scheduleData.map(item => item.classSection)
      return [...new Set(sections)].sort()
    }
  },
  
  onLoad() {
    this.init()
  },
  
  methods: {
    async init() {
      await this.getUserInfo()
      await this.loadScheduleData()
    },
    
    // 获取当前用户信息
    async getUserInfo() {
      try {
        const res = await getUserProfile()
        this.userInfo = res
        console.log('用户信息获取成功:', res)
      } catch (e) {
        console.error('获取用户信息失败', e)
        uni.showToast({ 
          title: '请先登录', 
          icon: 'none'
        })
      }
    },
    
    // 加载课程表数据
    async loadScheduleData() {
      if (!this.userInfo) {
        uni.showToast({ 
          title: '用户信息未加载', 
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '加载中...' })
        
        const teacherName = this.userInfo.nickname || this.userInfo.userName
        console.log('查询教师课程:', teacherName)
        
        // 调用新接口 - 注意这里需要修改 API 文件
        const res = await getTeacherSchedule({
          teacherName: teacherName,
          term: this.currentTerm || null
        })
        
        this.scheduleData = res || []
        console.log('课程数据:', this.scheduleData)
        
        if (this.scheduleData.length === 0) {
          uni.showToast({ 
            title: '暂无课程数据', 
            icon: 'none'
          })
        }
      } catch (e) {
        console.error('加载课程表失败', e)
        uni.showToast({ 
          title: '加载失败', 
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 根据时段和星期几获取课程
    getCourseByTime(classSection, dayOfWeek) {
      return this.scheduleData.find(item => 
        item.classSection === classSection && item.dayOfWeek === dayOfWeek
      )
    },
    
    // 单元格点击事件
    handleCellClick(classSection, dayOfWeek) {
      const course = this.getCourseByTime(classSection, dayOfWeek)
      if (course) {
        // 编辑已有课程
        this.editingCourse = { ...course }
        this.originalCourse = { ...course }
        this.showEditModal = true
      } else {
        // 添加新课程
        this.editingCourse = {
          id: null,
          term: this.currentTerm || '2024-2025-1', // 默认当前学期
          className: '',
          classSection,
          dayOfWeek,
          classroom: '',
          courseContent: '',
          isOwnCourse: false
        }
        this.originalCourse = null
        this.showEditModal = true
      }
    },
    
    // 获取星期标签
    getWeekDayLabel(dayOfWeek) {
      const day = this.weekDays.find(d => d.value === dayOfWeek)
      return day ? day.label : ''
    },
    
    // 关闭编辑弹窗
    closeEditModal() {
      this.showEditModal = false
      this.editingCourse = null
      this.originalCourse = null
    },
    
    // 提交编辑
    async submitEdit() {
      if (!this.editingCourse.courseContent || !this.editingCourse.courseContent.trim()) {
        uni.showToast({
          title: '请输入课程内容',
          icon: 'none'
        })
        return
      }
      if (!this.editingCourse.className || !this.editingCourse.classSection || !this.editingCourse.classroom) {
        uni.showToast({
          title: '班级、时间段、教室不能为空',
          icon: 'none'
        })
        return
      }
      try {
        uni.showLoading({ title: '提交中...' })
        // 冲突检测
        const conflictTeacher = await checkTimeConflict({
          classSection: this.editingCourse.classSection,
          classroom: this.editingCourse.classroom,
          dayOfWeek: this.editingCourse.dayOfWeek,
          excludeId: this.editingCourse.id
        })
        if (conflictTeacher) {
          uni.showModal({
            title: '时间冲突',
            content: `该时间段和教室已有 ${conflictTeacher} 老师的课程`,
            showCancel: false
          })
          uni.hideLoading()
          return
        }
        // 新增或修改
        await updateCourseContent({
          id: this.editingCourse.id,
          dayOfWeek: this.editingCourse.dayOfWeek,
          courseContent: this.editingCourse.courseContent,
          className: this.editingCourse.className,
          classSection: this.editingCourse.classSection,
          classroom: this.editingCourse.classroom
        }, this.userInfo.nickname || this.userInfo.userName)
        uni.showToast({
          title: this.editingCourse.id ? '修改成功' : '添加成功',
          icon: 'success'
        })
        this.closeEditModal()
        await this.loadScheduleData()
      } catch (e) {
        console.error('提交失败', e)
        uni.showToast({
          title: '提交失败: ' + (e.message || e),
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 刷新数据
    refreshData() {
      this.loadScheduleData()
    }
  }
}
</script>

<style lang="scss" scoped>
.schedule-container {
  padding: 0;
  background-color: #fff;
  min-height: 100vh;
}

.header-tip {
  background-color: #3c96f3;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  text {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 10rpx;
  }
  
  .tip-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
    font-weight: normal;
  }
}

.action-bar {
  display: flex;
  gap: 0;
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e8e8e8;
  
  button {
    flex: 1;
    height: 70rpx;
    line-height: 70rpx;
    font-size: 28rpx;
    border-radius: 6rpx;
    border: none;
  }
  
  .btn-refresh {
    background-color: #3c96f3;
    color: #fff;
  }
}

.table-scroll {
  width: 100%;
  white-space: nowrap;
}

.schedule-table {
  background-color: #fff;
  display: inline-block;
  min-width: 100%;
}

.table-header {
  display: flex;
  background-color: #3c96f3;
  
  .header-cell {
    padding: 18rpx 10rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #fff;
    border-right: 1rpx solid #fff;
    min-width: 180rpx;
    flex-shrink: 0;
    
    &:last-child {
      border-right: none;
    }
  }
  
  .time-cell {
    min-width: 240rpx;
  }
}

.table-body {
  .table-row {
    display: flex;
    border-bottom: 1rpx solid #e8e8e8;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .body-cell {
    padding: 12rpx;
    text-align: center;
    font-size: 24rpx;
    border-right: 1rpx solid #e8e8e8;
    min-width: 180rpx;
    height: 160rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    &:last-child {
      border-right: none;
    }
  }
  
  .time-cell {
    min-width: 240rpx;
    background-color: #f9f9f9;
    
    .time-label {
      font-size: 26rpx;
      font-weight: bold;
      color: #333;
      word-wrap: break-word;
      white-space: normal;
      text-align: center;
      line-height: 1.5;
    }
  }
  
  .schedule-cell {
    cursor: pointer;
    padding: 8rpx;
  }
  
  .schedule-item {
    width: 100%;
    height: 100%;
    padding: 10rpx;
    background-color: #3c96f3;
    border-radius: 4rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: flex-start;
    box-sizing: border-box;
    
    .course-line {
      width: 100%;
      word-break: break-word;
      white-space: normal;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
    
    .course-name {
      font-size: 24rpx;
      color: #fff;
      font-weight: bold;
    }
    
    .class-name {
      font-size: 22rpx;
      color: #fff;
    }
    
    .classroom {
      font-size: 20rpx;
      color: #fff;
    }
  }
  
  .empty-cell {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f9f9f9;
    border-radius: 4rpx;
    border: 1rpx dashed #d0d0d0;
    
    .empty-text {
      font-size: 26rpx;
      color: #999;
    }
  }
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 20rpx;
}

.popup-content {
  width: 100%;
  max-width: 700rpx;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 40rpx;
  max-height: 90vh;
  overflow-y: auto;
  box-sizing: border-box;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  
  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .form-item {
    margin-bottom: 30rpx;
    
    .form-label {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 12rpx;
    }
    
    .form-value {
      display: block;
      font-size: 28rpx;
      color: #666;
      height: 80rpx;
      line-height: 78rpx;
      padding: 0 20rpx;
      background-color: #f5f5f5;
      border-radius: 6rpx;
      border: 1rpx solid #e8e8e8;
    }
    
    .form-input {
      width: 100%;
      height: 80rpx;
      padding: 0 20rpx;
      background-color: #fff;
      border-radius: 6rpx;
      border: 1rpx solid #d0d0d0;
      font-size: 28rpx;
      color: #333;
      box-sizing: border-box;
      line-height: 78rpx;
      transition: all 0.3s;
      
      &:focus {
        border-color: #3c96f3;
        outline: none;
        box-shadow: 0 0 0 2rpx rgba(60, 150, 243, 0.1);
      }
    }
  }
  
  .popup-buttons {
    display: flex;
    gap: 16rpx;
    margin-top: 40rpx;
    
    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      border-radius: 6rpx;
      border: none;
      transition: all 0.3s;
      
      &:active {
        transform: scale(0.98);
      }
    }
    
    .btn-cancel {
      background-color: #f5f5f5;
      color: #666;
      border: 1rpx solid #d0d0d0;
    }
    
    .btn-confirm {
      background-color: #3c96f3;
      color: #fff;
    }
  }
}
</style>
